import React from 'react';
import {Spin, Card, Button, Table, Row, Col, Form} from 'antd';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import PropTypes from 'prop-types';
import {saleOrderPriceTerms, saleOrderTransportTypeForKd, paymentType, currency} from '../Enum';
import routes from './routes';
import {DATE_FORMAT, TABLE, FORM_OPTIONS} from '../constants';
import {conventEnumValueToString, formatDateTime, formatAmount} from '../utils';
import {getDetail, confirmData} from './api';
import {injectIntl} from './intl';
import FileUpload from './FileUpload';
import styles from './style.css';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {confirmValidator} from './validator';
import Return from '../common/Return';
const {Description} = DescriptionList;
const EMPTY_ARRAY = [];
const FormItem = Form.Item;
class ConfirmPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {},
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        subPIPlacements: res.data.subPIPlacements,
                        subPIDetails: res.data.subPIDetails.map(d => Object.assign({}, d, {
                            order: res.data.subPIDetails.findIndex(x => x.id === d.id) + 1,
                        })),
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onSubmit = () => {
        this.setState({
            loading: true
        });
        const {data} = this.state;
        const condition = {
            rowVersion: data.rowVersion,
            attachments: (data.attachments || []).map(v => ({
                fileId: v.fileId,
                fileName: v.fileName
            }))
        };
        const isValid = confirmValidator(condition);
        if(!isValid) {
            this.setState({
                validate: true,
                loading: false
            });
            return;
        }
        confirmData(data.id, condition).then(res => {
            if(res.ok)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onCancel = () => {
        this.props.history.push(routes.query.url());
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    render() {
        const {data, subPIPlacements, subPIDetails, loading} = this.state;
        const confirmable = !hasPermissions(PERMISSION.confirm, this.props.permissions);
        const {formatMessage} = this.props.intl;
        let totalAmount = 0;
        let totalQuantity = 0;
        let totalAmountSum = 0;
        let totalQuantitySum = 0;
        if(subPIDetails)
            subPIDetails.forEach(v => {
                totalAmount += ((v.quantity ? v.quantity : 0) * (v.price ? v.price : 0));
                totalQuantity += v.quantity;
            });
        if(subPIPlacements)
            subPIPlacements.forEach(v => {
                totalAmountSum += ((v.quantity ? v.quantity : 0) * (v.price ? v.price : 0));
                totalQuantitySum += v.quantity;
            });
        const columns = [{
            title: formatMessage({
                id: 'newPanel.column.placement',
                defaultMessage: '配置'
            }),
            dataIndex: 'placement',
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.amount',
                defaultMessage: '金额'
            }),
            dataIndex: 'amount',
            render: (text, record) => formatAmount((record.price) * (record.quantity))
        }, {
            title: formatMessage({
                id: 'newPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
        }];
        const partColumns = [{
            title: formatMessage({
                id: 'newPanel.column.order',
                defaultMessage: '序号'
            }),
            dataIndex: 'order',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partCode',
                defaultMessage: '备件编号'
            }),
            dataIndex: 'partCode',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partNameInChinese',
                defaultMessage: '备件名称'
            }),
            dataIndex: 'partNameInChinese',
        }, {
            title: formatMessage({
                id: 'newPanel.column.partNameInEnglish',
                defaultMessage: '备件英文名称'
            }),
            dataIndex: 'partNameInEnglish',
        }, {
            title: formatMessage({
                id: 'newPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity',
        }, {
            title: formatMessage({
                id: 'newPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'newPanel.column.amount',
                defaultMessage: '金额'
            }),
            dataIndex: 'amount',
            render: (text, record) => formatAmount((record.price) * (record.quantity))
        }, {
            title: formatMessage({
                id: 'newPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark',
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'confirm.column.common',
                        defaultMessage: '基本信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={formatMessage({
                                            id: 'confirm.operation.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {(data.brandCode) + data.brandName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.batchNumber',
                                        defaultMessage: '批次号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.batchNumber}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.piCode',
                                        defaultMessage: '发票号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.piCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.productionMonth',
                                        defaultMessage: '产品月份'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.productionMonth}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.title',
                                        defaultMessage: '标题'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.title}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.cargoDescription',
                                        defaultMessage: '货描'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.cargoDescription}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.model',
                                        defaultMessage: '车型编号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.model}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.supplierName',
                                        defaultMessage: '供应商名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.supplierName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.currency',
                                        defaultMessage: '币种'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(currency, data.currency)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.tradeMethodName',
                                        defaultMessage: '贸易方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.tradeMethodName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.salesOrderPriceTerms',
                                        defaultMessage: '价格条款'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(saleOrderPriceTerms, data.salesOrderPriceTerms)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.paymentType',
                                        defaultMessage: '付款方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(paymentType, data.paymentType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirm.form.productAmount',
                                            defaultMessage: '备件总金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatAmount(data.productAmount)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirm.form.typeAmount',
                                            defaultMessage: '货物总金额'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatAmount(data.typeAmount)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.deliveryTerms',
                                        defaultMessage: '运输方式'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(saleOrderTransportTypeForKd, data.deliveryTerms)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.shippingPortName',
                                        defaultMessage: '发运港口'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.shippingPortName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.destinationPort',
                                        defaultMessage: '目的港口'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.destinationPort}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.bankAccount',
                                        defaultMessage: '银行账号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.bankAccount}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.bankName',
                                        defaultMessage: '银行名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.bankName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.bankNameEng',
                                        defaultMessage: '银行英文名称'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.bankNameEng}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.swift',
                                        defaultMessage: '银行识别码'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.swift}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.bankAccount',
                                        defaultMessage: '银行账号'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.bankAccount}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'confirm.form.createTime',
                                            defaultMessage: '提报日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.createTime, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.creatorName',
                                        defaultMessage: '创建人姓名'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.creatorName}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'confirm.operation.remark',
                                        defaultMessage: '备注'
                                    })} {...FORM_OPTIONS.item}>
                                        {data.remark}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: 'Sub PI配置清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={subPIPlacements}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '数量汇总'
                                    })}>{totalQuantitySum ? totalQuantitySum : null}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '金额汇总'
                                    })}>{formatAmount(totalAmountSum ? totalAmountSum : null)}
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.subPIDetails',
                            defaultMessage: 'Sub PI清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={partColumns}
                                rowKey="id"
                                pagination={false}
                                dataSource={subPIDetails}
                                footer={() => <DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalQuantity',
                                        defaultMessage: '数量汇总'
                                    })}>{totalQuantity ? totalQuantity : null}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'newPanel.operation.totalAmount',
                                        defaultMessage: '金额汇总'
                                    })}>{formatAmount(totalAmount ? totalAmount : null)}
                                    </Description>
                                </DescriptionList>}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card title={formatMessage({
                        id: 'reportPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={data.attachments || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!confirmable}
                            loading={loading}>
                            {formatMessage({
                                id: 'confirm.operation.confirm',
                                defaultMessage: '确认'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickReturnBtn}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

ConfirmPanel.propTypes = {
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object
};

import {connect} from 'react-redux';
import {tableSearch} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(ConfirmPanel));
